package com;
/**
 * @author 吴宇~
 * @motto 我亦无他，唯手熟尔。
 * @edition jdk1.8
 * @reflection 0-1 喧闹任其喧闹，自由我自为之，我自风情万种，与世无争。
 * @person Han Xiaojiu
 */

import javax.sound.sampled.*;
import java.io.*;

/**
 * @author ajun
 * Date 2021/7/16
 * @version 1.0
 * 播放音乐
 */
public class PlayAudio extends Thread {
    private String filename;
    public PlayAudio(String wavfile) {
        filename =  wavfile;
    }
    private static Hero hero=null;

    public static void setHero(Hero hero) {
        PlayAudio.hero = hero;
    }

    @Override
    public void run() {
        // 从项目资源目录下加载背景音乐
        AudioInputStream audioInputStream = null;
        try {
            audioInputStream = AudioSystem.getAudioInputStream(new BufferedInputStream(new FileInputStream(filename)));
        } catch (Exception e1) {
            e1.printStackTrace();
            return;
        }

        AudioFormat format = audioInputStream.getFormat();
        SourceDataLine auline = null;
        DataLine.Info info = new DataLine.Info(SourceDataLine.class, format);

        try {
            auline = (SourceDataLine) AudioSystem.getLine(info);
            auline.open(format);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        auline.start();
        int nBytesRead = 0;
        //缓存
        byte[] abData = new byte[512];

        try {
            while (nBytesRead != -1) {
                nBytesRead = audioInputStream.read(abData, 0, abData.length);
                if (nBytesRead >= 0)
                    auline.write(abData, 0, nBytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return;
        } finally {
            auline.drain();
            auline.close();
        }
        //想做一个让自己死亡之后音乐不再播放的程序，
//        while(true){
//            sleep();
//            if (!hero.isLive){
//                try {
//                    Thread.sleep(1000000000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//                break;
//            }
//        }
    }
//    public void sleep(){
//        try {
//            Thread.sleep(1000);
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
//    }

}


